<!--
 * @Description: 创建生产批次页面
-->
<template>
  <BaseMainSlot>
    <!-- <template v-slot:tab-box>
      <label>批次类型:</label>
      <SelectButton :buttonselectlist="batchTypeList" @nowselectbuttonindex="batchChange" />
    </template> -->
    <template v-slot:btn-box>
      <SelectButton :buttonselectlist="buttonselectlist" @nowselectbuttonindex="batchstaumet" />
      <ActionBar
        :page-no="24"
        :add-active="addActive"
        :del-active="delActive"
        :has-edit="false"
        :has-cancel="false"
        :has-save="false"
        :has-edit-column="true"
        @showColumn="showColumn"
        @add="add"
        @del="del"
      />
    </template>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"
        @getPlantVarietyList="getPlantVarietyList"></SearchForm>
    </template>
    <template v-slot:table-box>
      <Table @sortChange="changeTableSort" :propList="tableColumn" v-loading="loading"
        :listData="tableData" @handleSelectionChange="handleSelectionChange">
        <template v-slot:operation="{ row }">
          <template v-if="!row.index && row.batchId">
            <el-button class="text-btn-cursor" type="text" size="small" @click.stop="dbhandleEdit(row)"><i class="el-icon-view"></i> 查看</el-button>
            <!-- :disabled="row.applyStatus !== 1" -->
            <el-button
              v-if="judgePermission(24, 'edit') && row.finishStatus!=='FINISH'"
              class="text-btn-cursor"
              type="text"
              size="small"
              style="height: 15px"
              @click="dbhandleEdit(row, 'edit')"
            ><i class="el-icon-edit-outline" ></i> 修 改</el-button>
            <el-button v-if="judgePermission(24, 'delete')" class="text-btn-cursor cursor-delete" type="text" size="small" @click="handleDelete(row)"><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </template>
        <template v-slot:facilities="{ row, item }">
          <template v-if="!row.index && row.batchId">
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="checkFacility(row, item.prop)"
            >
              <i class="el-icon-view"></i> 查看
            </el-button>
          </template>
        </template>
        <template v-slot:cycle="{ row }">
          <template v-if="!row.index && row.batchId">
            <span v-if="row.cycle || row.plantingPeriodType">
              {{ row.plantingPeriodType == 'SEASONS' ? '多季作物' : row.cycle + "天" }}
            </span>
            <template v-else>—</template>
          </template>
        </template>
        <template v-slot:area="{ row }">
          <template v-if="!row.index && row.batchId">
            {{ row.area }}{{ row.areaUnitName }}
          </template>
        </template>
        <template v-slot:assetValue="{ row }">
          <template v-if="!row.index && row.batchId">
            {{ row.assetValue }}{{ row.assetUnitName }}
          </template>
        </template>
        <template v-slot:lesseeName="{ row, item }">
          <template v-if="!row.index && row.batchId">
            {{ row[item.prop] || "—" }}
          </template>
        </template>
      </Table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <!-- <template v-slot:form> -->
    <!-- </template> -->
    <template v-slot:dialog>
      <el-dialog
        :title="dialogtitle + '生产批次信息'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          class="el-form"
          :rules="rules"
        >
          <!-- <el-form-item label="批次名称" prop="dataItemName" class="w50p">
          <el-select v-model="formData.nowdataItemList" clearable :disabled="!canInput">
            <el-option v-for="(item,index) in dataItemList" :key="index" :label="item.dataItemName" :value="index" />
          </el-select>
        </el-form-item> -->
          <el-form-item label="种植设施:" :required="true" class="w50p">
            <el-form-item
              class="w100p"
              style="width: calc(50% - 10px) !important; padding-left: 0 !important"
            >
              <el-select
                v-model="facilityGroupNo"
                clearable
                filterable
                :disabled="!canInput"
                placeholder="地块组:"
                @change="groupfacilychange"
              >
                <el-option
                  v-for="(item, index) in groupFacilyList"
                  :key="index"
                  :label="item.facilityGroupName"
                  :value="item.facilityGroupNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              class="w100p"
              prop="selectfacilyindexlist"
              style="width: calc(50% - 10px) !important; padding-left: 0 !important; margin-left: 20px"
            >
              <el-select
                v-model="formData.selectfacilyindexlist"
                multiple
                collapse-tags
                clearable
                filterable
                :disabled="!canInput"
                placeholder="组中地块:"
              >
                <el-option
                  v-for="item in facilyList"
                  :key="item.facilityNo"
                  :label="item.facilityName"
                  :value="item.facilityNo"
                />
              </el-select>
            </el-form-item>
          </el-form-item>
          <el-form-item label="批次名称:" prop="batchName" class="w50p">
            <el-input
              v-model="formData.batchName"
              :disabled="!canInput"
              clearable
            />
          </el-form-item>
          <el-form-item label="批次号:" prop="batchNo" class="w50p">
            <!-- <el-form-item v-if="nowChanceStau.length === 0" label="批次号" prop="batchNo" class="w50p"> -->
            <el-input v-model="formData.batchNo" disabled clearable />
          </el-form-item>
          <el-form-item label="种植方式:" prop="mode" class="w50p">
            <el-select
              v-model="formData.mode"
              clearable
              :disabled="!canInput"
              placeholder="选择方式"
              filterable
            >
              <el-option
                v-for="(item, index) in plantmodelist"
                :key="index"
                :label="item.putIntoModeName"
                :value="item.putIntoModeName"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item
            v-if="nowChanceStau.length === 0"
            label="完成时间:"
            prop="completionDays"
            class="w50p"
          >
            <el-date-picker
              v-model="formData.completionDays"
              value-format="yyyy-MM-dd HH-mm-ss"
              type="datetime"
              :disabled="!canInput"
              placeholder="--"
            />
          </el-form-item> -->
          <el-form-item
            label="承租户姓名:"
            prop="lesseeName"
            class="w50p"
          >
            <!-- <el-form-item label="承租户姓名" prop="lesseeName" class="w50p"> -->
            <!-- <el-input v-model="formData.lesseeName" disabled clearable /> -->
            <el-select
              v-model="formData.lesseeNo"
              clearable
              :disabled="!canInput"
              placeholder="承租户"
              filterable
            >
              <el-option
                v-for="(item, index) in lesseeList"
                :key="index"
                :label="item.lesseeName"
                :value="item.lesseeNo"
              />
            </el-select>
            <!-- lesseeList -->
          </el-form-item>
          <el-form-item label="种植类别:" :required="true" class="w50p">
            <el-form-item
              class="w100p"
              prop="plantingTypeNo"
              style="width: calc(50% - 10px) !important; padding-left: 0 !important"
            >
              <el-cascader
                v-model="formData.plantingTypeNo"
                :disabled="!canInput"
                :props="{
                  value: defaultProps.value,
                  children: defaultProps.children,
                  label: defaultProps.label,
                  emitPath: false,
                  checkStrictly: true
                }"
                placeholder="种植类别"
                :options="planttypeList"
                :show-all-levels="true"
                clearable
                filterable
                @change="getpingzghong"
              />
            </el-form-item>
            <el-form-item
              class="w100p"
              prop="varietyNo"
              style="width: calc(50% - 10px) !important; padding-left: 0 !important; margin-left: 20px"
            >
              <el-select
                v-model="formData.varietyNo"
                clearable
                :disabled="!canInput"
                placeholder="种植品种"
                filterable
              >
                <el-option
                  v-for="(item, index) in nowvarietyList"
                  :key="index"
                  :label="item.plantVarietyName"
                  :value="item.plantVarietyNo"
                />
              </el-select>
            </el-form-item>
          </el-form-item>
          <el-form-item label="种植周期:" prop="plantingPeriodType" class="w50p">
              <el-select
                v-model="formData.plantingPeriodType"
                clearable
                :disabled="!canInput"
                placeholder="种植品种"
                filterable
              >
                <el-option label="多季作物" value="SEASONS" />
                <el-option label="输入天数" value="DAYS" />
              </el-select>
          </el-form-item>
          <el-form-item label="周期（天）:" v-if="formData.plantingPeriodType === 'DAYS'" prop="cycle" class="w50p">
            <el-input
              v-model="formData.cycle"
              type="number"
              min="0"
              @input="numChange('cycle')"
              :disabled="!canInput"
              clearable
            />
          </el-form-item>
          <el-form-item label="种植规模:" prop="area" class="w50p">
            <el-form-item
              class="w100p"
              style="width: calc(50% - 10px) !important; padding-left: 0 !important"
              prop="area"
            >
              <el-input
                v-model="formData.area"
                type="number"
                min="0"
                @input="numChange('area')"
                :disabled="!canInput"
                clearable
              />
            </el-form-item>
            <el-form-item
              class="w100p"
              style="width: calc(50% - 10px) !important; padding-left: 0 !important; margin-left: 20px"
              prop="areaUnitNo"
            >
              <el-select
                v-model="formData.areaUnitNo"
                clearable
                :disabled="!canInput"
                filterable
                placeholder="请选择"
                @change="areaUnitlist"
              >
                <el-option
                  v-for="(item, index) in scaleUnitList"
                  :key="index"
                  :label="item.unitName"
                  :value="item.unitNo"
                />
              </el-select>
            </el-form-item>
          </el-form-item>
          <!-- s -->
          <el-form-item label="投产量:" v-if="batchType === 0"
            style="margin-bottom: 40px !important" class="w50p" :required="true">
            <el-form-item
              class="w100p"
              style="width: calc(65% - 20px) !important; padding-left: 0 !important"
              prop="assetValue"
            >
              <el-input
                v-model.number="formData.assetValue"
                type="number"
                min="0"
                @input="numChange('assetValue')"
                :disabled="!canInput"
                clearable
              />
            </el-form-item>
            <el-form-item
              class="w100p"
              style="width: 35% !important; padding-left: 0 !important; margin-left: 20px"
            >
              <el-select
                v-model="formData.assetUnitNo"
                clearable
                :disabled="!canInput"
                filterable
                placeholder="斤"
              >
                <el-option
                  v-for="(item, index) in plantunitList"
                  :key="index"
                  :label="item.unitName"
                  :value="item.unitNo"
                />
              </el-select>
            </el-form-item>
          </el-form-item>
          <el-form-item label="投产日期:" v-if="batchType === 0" prop="assetDate" class="w50p">
            <el-date-picker
              v-model="formData.assetDate"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              type="date"
              :disabled="!canInput"
              placeholder="选择投产时间"
              filterable
              :picker-options="pickerOptions"
              @change="timeChange"
            />
            <!-- <el-input
            v-model="formData.assetDate"
            :disabled="!canInput"
            clearable
          /> -->
          </el-form-item>
          <el-form-item label="种植数量:" v-if="batchType === 1" prop="batchNum" class="w50p">
            <el-input
              v-model="formData.batchNum"
              type="number"
              min="0"
              @input="numChange('batchNum')"
              @change="loadNo"
              :disabled="!canInput"
              clearable
            />
          </el-form-item>
          <el-form-item label="种植日期:" v-if="batchType === 1" prop="assetDate" class="w50p">
            <el-date-picker
              v-model="formData.assetDate"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              type="date"
              :disabled="!canInput"
              placeholder="选择种植日期"
              filterable
            />
          </el-form-item>
          <el-form-item label="已种植天数:" style="margin-bottom: 40px !important" prop="completionDays" class="w50p">
            <!-- placeholder="批次创建时已完成时间" -->
            <el-input
              v-model="formData.completionDays"
              type="number"
              min="0"
              @input="numChange('completionDays')"
              :disabled="!canInput"
              placeholder="请输入种植天数"
              clearable
            />
          </el-form-item>
          <el-form-item label="备注:" class="w50p">
            <el-input
              v-model="formData.description"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
              :disabled="!canInput"
              clearable
            />
          </el-form-item>
          <el-form-item label="编号:" v-if="batchType === 1" prop="singleNoList" class="w100p">
            <template v-for="item,index in formData.singleNoList">
              <el-input
                v-model="formData.singleNoList[index]"
                :disabled="!canInput"
                style="width: 160px; margin: 0 5px 5px 0;"
              />
            </template>
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">
            取 消
          </el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >
            保 存
          </el-button>
        </div>
      </el-dialog>
      <el-dialog
        :title="dialogtitle + '生产批次信息'"
        :visible.sync="dialogRecVisible"
        width="33"
        class="dialogRec"
      >
        <span>批次创建完成之后不可修改，请确认批次信息是否填写正确！！！</span>
        <span slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            class="correct"
            @click="dialogRecVisible = false"
          >
            重新确认
          </el-button>
          <el-button
            type="success"
            class="Reconfirmation"
            plain
            @click="saveAdd()"
          >
            确认无误
          </el-button>
        </span>
      </el-dialog>
      <el-dialog :title="facilityDialogType == 'facility' ? '设施列表' : '编号列表'" :visible="facilityDialogVisible"
        class="dialogRec" :before-close="()=>{facilityDialogVisible = false}">
        <div class="facility-list">
          <div v-for="(item,index) in batchFacilityMapperList" :key="index" class="facility-item">
            <div v-if="facilityDialogType == 'facility'" class="info-line">
              <div class="name">设施编号：</div><div class="value">{{ item.facilityNo }}</div>
            </div>
            <div v-if="facilityDialogType == 'facility'" class="info-line">
              <div class="name">设施名称：</div><div class="value">{{ item.facilityName }}</div>
            </div>
            <div v-else class="info-line">
              <div class="name">编号：</div><div class="value">{{ item }}</div>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="facilityDialogVisible = false">
            关 闭
          </el-button>
        </div>
      </el-dialog>
      <el-dialog
        id="tableColumnDialog"
        title="配置列"
        :visible.sync="dialogTableColumnVisible"
      >
        <tableColumn
          v-if="dialogTableColumnVisible"
          ref="tableColumn"
          :tableColumn="allTableColumn"
          :pathsuffix="batchType"
          @cancelColumn="cancelColumn"
        />
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="dialogTableColumnVisible = false">
            取 消
          </el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="saveColumn"
          >
            保 存
          </el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import Table from '@/components/table/table.vue';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import nowpagereq from "@/api/digital-production/production-batch-manage/create-production-batch/index";
import unitreq from "@/api/basic-info-manage/unit-manage/index";
import zhongyangleibie from "@/api/basic-info-manage/category-management/index";
import zhongyangpizhong from "@/api/basic-info-manage/breed-varieties-management/index";
import getunit from "@/api/basic-info-manage/unit-manage/index";
import landgroupInfoManage from "@/api/digital-operation/land-manage/land-group-manage";
// import BaseMainSlot from "@/components/BaseMainSlot"
// 查询条件
import nowstage from "@/api/digital-production/growth-record-management/growth-stage-division/index";
// import tenantInfo from "@/api/digital-operation/tenant-manage/tenant-info/index";
// import StartTimeEndTimeSelectionBox from "@/components/StartTimeEndTimeSelectionBox";

import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import SelectButton from "@/components/selectbutton/index.vue";
import { mymixin } from "@/utils/mixin";
import { getToken } from "@/utils/auth";
import { mapGetters } from "vuex";
export default {
  name: "CreateProductionBatch",
  components: { SearchForm, Table, ActionBar, Pagination, BaseMainSlot, SelectButton },
  mixins: [mymixin],
  data() {
    return {
      batchType: 0,
      batchTypeList: [{ name: "批次管理" }, { name: "单个管理" }],
      buttonselectlist: [{ name: "全部" }, { name: "未完成批次" }, { name: "已完成批次" }],
      tableColumn: [
        { prop: 'batchName', label: '批次名称', minWidth: '200' },
        { prop: 'batchNo', label: '批次号', minWidth: '150' },
        { prop: 'facilities', label: '种植设施', slotName: 'facilities', minWidth: '110' },
        { prop: 'mode', label: '种植方式', slotName: 'lesseeName', minWidth: '110' },
        { prop: 'plantingTypeName', label: '种植类别', minWidth: '110' },
        { prop: 'varietyName', label: '种植品种', minWidth: '110' },
        { prop: 'cycle', label: '种植周期', slotName: 'cycle', minWidth: '110' },
        { prop: 'area', label: '种植规模', slotName: 'area', minWidth: '110' },
        { prop: 'assetDate', label: '投产日期', minWidth: '110' },
        { prop: 'assetValue', label: '投产量', slotName: 'assetValue', minWidth: '110' },
        { prop: 'lesseeName', label: '承租户', slotName: 'lesseeName', minWidth: '110' },
        { prop: 'completionDate', label: '完成日期', slotName: 'lesseeName', width: '110' },
        { prop: 'operation', label: '操作', slotName: 'operation', width: "200" }
      ],
      tableColumn2: [
        { prop: 'batchName', label: '批次名称', minWidth: '200' },
        { prop: 'batchNo', label: '批次号', minWidth: '150' },
        { prop: 'facilities', label: '种植设施', slotName: 'facilities', minWidth: '110' },
        { prop: 'mode', label: '种植方式', slotName: 'lesseeName', minWidth: '110' },
        { prop: 'plantingTypeName', label: '种植类别', minWidth: '110' },
        { prop: 'varietyName', label: '种植品种', minWidth: '110' },
        { prop: 'cycle', label: '种植周期', slotName: 'cycle', minWidth: '110' },
        { prop: 'batchNum', label: '种植数量', minWidth: '110' },
        { prop: 'singleNos', label: '单个编号', slotName: 'facilities', minWidth: '110' },
        { prop: 'assetDate', label: '种植日期', minWidth: '110' },
        { prop: 'lesseeName', label: '承租户', slotName: 'lesseeName', minWidth: '110' },
        { prop: 'operation', label: '操作', slotName: 'operation', width: "200" }
      ],
      formConfig: [
        {
          label: '批次名称',
          prop: 'batchName',
          type: 'input',
        }, {
          label: '批次号',
          prop: 'batchNo',
          type: 'select',
          options: [], // allbatchList
          optionKey: { label: 'batchNo', value: 'batchNo' },
        }, {
          label: '设施名称',
          prop: 'facilityNo',
          type: 'select',
          options: [], // facilyList
          optionKey: { label: 'facilityName', value: 'facilityNo' }
        }, {
          label: '承租户',
          prop: 'lesseeNo',
          type: 'select',
          options: [], // lesseeList
          optionKey: { label: 'lesseeName', value: 'lesseeNo' }
        }, {
          label: '种植类别',
          prop: 'selectplantlist',
          type: 'cascader',
          options: [], // planttypeList
          change: 'getPlantVarietyList',
          optionKey: {
            expandTrigger: 'hover',
            value: 'plantTypeNo',
            children: 'children',
            label: 'plantTypeName',
            checkStrictly: true
          }
        }, {
          label: '种植品种',
          prop: 'plantVarietyNo',
          type: 'select',
          options: [], // plantVarietyList
          optionKey: { label: 'plantVarietyName', value: 'plantVarietyNo' }
        }, {
          label: '投产日期',
          prop: 'date',
          type: 'daterange',
        },
      ],
      newtotalSize: 0,
      // 一般为农业类型id
      farmingTypeNo: "",
      // 所搜索框内容
      searchName: "",
      // 下拉选择框相关
      selectplantlist: [],
      nowplantTypeName: "",
      planttypeList: [],
      nowvarietyList: [],
      plantVarietyList: [],
      lesseeList: [],
      // 种养方式
      plantmodelist: [
        // { name: "插秧" },
        // { name: "直播" },
        // { name: "苗种" },
        // { name: "放苗" }
      ],
      formData: {
        batchNo: "",
        selectfacilyindexlist: [],
        batchName: "",
        assetDate: "",
        mode: "",
        plantingTypeNo: "",
        varietyNo: "",
        assetValue: "",
        assetUnitNo: "",
        area: "",
        areaUnitNo: "",
        areaUnit: "",
        cycle: "",
        completionDays: "",
        description: "",
        batchFacilityMapperList: [],
        farmingTypeNo: "",
        lesseeName: "",
        lessesNo: "",
        organizationNo: ""
        // status: false
      },
      // 地块组列表
      groupFacilyList: [],
      scaleUnitList: [],
      facilityGroupNo: "", // 当前地块组id
      // 查询条件
      facilityNo: "",
      organizationNo: "",
      batchNo: "",
      lesseeNo: "",
      plantVarietyNo: "",
      searchlist: {},
      // 地块信息详细列表
      facilyList: [],
      selectfacilyindexlist: [], // 选中的地块
      plantunitList: [],
      // 当前表格选择的数组
      nowSelectList: [],
      allbatchList: [],
      // 所搜索框内容
      dialogRecVisible: false,
      dialogFormVisible: false,
      dialogtitle: "",
      rules: {
        batchNo: [
          { required: true, message: "请输入批次号！！！", trigger: "blur" }
        ],
        batchName: [
          { required: true, message: "请输入批次名称！！！", trigger: "blur" }
        ],
        assetDate: [
          { required: true, message: "请选择投产时间！！！", trigger: "change" }
        ],
        mode: [
          { required: true, message: "请选择种植方式！！！", trigger: "change" }
        ],
        plantingTypeNo: [
          { required: true, message: "请选择种植类别！！！", trigger: "change" }
        ],
        varietyNo: [
          { required: true, message: "请选择种植品种！！！", trigger: "change" }
        ],
        selectfacilyindexlist: [
          { required: true, message: "请选择设施！！！", trigger: "change" }
        ],
        assetValue: [
          { required: true, message: "请输入投产量！！！", trigger: "change" }
          // { validator: validateAssetValue, trigger: "blur" }
        ],
        area: [
          { required: true, message: "请输入种植规模！！！", trigger: "change" }
        ],
        areaUnitNo: [
          { required: true, message: "请选择面积单位！！！", trigger: "change" }
        ],
        plantingPeriodType: [
          { required: true, message: "请选择种植周期！！！", trigger: "change" }
        ],
        cycle: [
          { required: true, message: "请输入周期(天)！！！", trigger: "change" }
        ],
        completionDays: [
          { required: true, message: "请输入种植天数！！！", trigger: "change" }
        ]
      },
      defaultProps: {
        children: "children",
        value: "plantTypeNo",
        label: "plantTypeName"
      },
      batchRow: null,
      batchFacilityMapperList: [],
      facilityDialogVisible: false,
      facilityDialogType: '',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    nowChanceStau(newval) {
      if (newval) {
        this.getselectdatalist();
        this.getBatchList();
      }
      // this.nowplantTypeName = "种养类别"
      // if (newval === "add") {
      //   this.formData.batchNo = this.addcode
      // }
    },
    dialogFormVisible(v) {
      if (v) {
        this.$nextTick(()=>{
          this.$refs.formData.clearValidate()
        })
      }
    }
  },
  created() {
    this.tableColumn1 = [ ...this.tableColumn ]
  },
  mounted() {
    this.setplantmode();
    this.chancefarmtype(getToken("farmingTypeNo"));
  },
  methods: {
    timeChange() {
      let day = (Date.now() - new Date(this.formData.assetDate)) / (24 * 60 * 60 * 1000)
      this.$set(this.formData, 'completionDays', Math.trunc(day))
    },
    checkFacility(row, prop) {
      if (row.batchNo) {
        if (prop == 'facilities') {
          this.facilityDialogType = 'facility'
          this.batchFacilityMapperList = row.batchFacilityMapperList || [];
        } else {
          this.facilityDialogType = 'singleNos'
          this.batchFacilityMapperList = row.singleNos?.split(',') || [];
        }
        this.facilityDialogVisible = true;
      }
    },
    // 获取编号
    async loadNo(e) {
      if (e) {
        nowpagereq.addcodeNum(e).then(res => {
          if (res.code != 1) {
            this.$message.error(res.msg)
          }
          this.$set(this.formData, 'singleNoList', res.data?.split(','))
        })
      } else {
        this.$set(this.formData, 'singleNoList', [])
      }
    },
    // 批次类型切换
    batchChange(i) {
      if (i === 0) {
        this.tableColumn = [...this.tableColumn1]
        this.allTableColumn = [...this.tableColumn1]
      } else {
        this.tableColumn = [...this.tableColumn2]
        this.allTableColumn = [...this.tableColumn2]
      }
      this.batchType = i
      this.tableData = [];
      this.getBatchList();
      this.loadSaveColumn()
      this.search();
    },
    // 设置可选择的种养方法
    setplantmode() {
      let farmid = getToken("farmingTypeNo");
      unitreq.getmodeByCondition(farmid).then(
        res => {
          if (res.code === 1) {
            this.plantmodelist = res.data
          }
        }
      )
      // if (farmid === 'dt') {
      //   this.plantmodelist = [
      //     { name: "插秧" },
      //     { name: "直播" },
      //     { name: "苗种" }
      //   ];
      // } else if (farmid === 'dp') {
      //   this.plantmodelist = [{ name: "直播" }, { name: "苗种" }, { name: "水培" }, { name: "基质培" }, { name: "栽培" }];
      // } else if (farmid === 'xm') {
      //   this.plantmodelist = [{ name: "繁育" }];
      // } else if (farmid === 'sc') {
      //   this.plantmodelist = [{ name: "放苗" }];
      // } else if (farmid === 'gc') {
      //   this.plantmodelist = [{ name: "放苗" }];
      // }
    },
    // 获取单位名称
    async getUnitByCondition(No) {
      let unitName = "斤"
      await unitreq.getUnitByCondition(No).then(
        res => {
          if (res.data[0]) {
            unitName = res.data[0].unitName
          }
        }
      )
      return unitName
    },
    async addcode() {
      let res = await nowpagereq.addcode();
      if (res.code === 1) {
        let codenumber = res.data;
        return codenumber;
      } else if (res.code === -5) {
        this.$message.warning(res.msg)
        return '';
      }

      // console.log(res)
    },
    // 在有农业类型的页面中以此方法为获取表格方法
    chancefarmtype(e) {
      this.getselectdatalist();
      this.getBatchList();
      this.farmingTypeNo = e;
      // 获取表格数据
      this.getTableDataList();
    },
    // 获取下拉框数据
    async getselectdatalist() {
      // 获取种养类别列表
      // 获取种养类别树状表
      zhongyangleibie.getplantingTypeTree().then(res => {
        let list = res.data;
        this.planttypeList = this.filterArrForKey(list);
        this.formConfig[4].options = this.filterArrForKey(list);
      });

      // 获取产量单位
      getunit.getallunitlist({ unitTypeNo: "1001491616960118784" }).then(res => {
        this.plantunitList = res.data;
      });
      // 获取面积单位
      getunit.getallunitlist({ unitTypeNo: "995416636939862016" }).then(res => {
        this.scaleUnitList = res.data;
      });
      // 获取地块组列表
      landgroupInfoManage.getfacilityGroupAll().then(res => {
        this.groupFacilyList = res.data;
      });
      // 获取地块组列表
      nowpagereq.queryLessesByCondition().then(res => {
        this.lesseeList = res.data;
        this.formConfig[3].options = res.data;
      });
      let params = {};
      if (this.nowChanceStau === "add") {
        params = {
          organizationNo: sessionStorage.getItem("organizationNo"),
          farmingTypeNo: sessionStorage.getItem("farmingTypeNo"),
          facilityStatus: false
        };
      } else {
        params = {
          organizationNo: sessionStorage.getItem("organizationNo"),
          farmingTypeNo: sessionStorage.getItem("farmingTypeNo")
        };
      }
      landgroupInfoManage.getqueryAllList(params).then(res => {
        this.facilyList = res.data.filter(el => { return el.facilityTypeName == '种养设施' });
        this.allfacilyList = res.data;
        this.formConfig[2].options = res.data;
      });

      this.getPlantVarietyList()
    },
    // 条件查询所有批次
    getBatchList() {
      // 条件查询所有批次
      let partwo = {
        organizationNo: getToken('organizationNo'),
        farmingTypeNo: getToken('farmingTypeNo'),
        batchType: this.batchType === 0 ? 'BATCH' : 'SINGLE',
        simpleData: true
      }
      nowpagereq.querybyname(partwo).then(
        restwo => {
          let listtwo = restwo.data
          this.allbatchList = listtwo
          this.formConfig[1].options = listtwo;
        }
      )
    },
    //  获取品种名称
    getPlantVarietyList(param) {
      let params = {
        plantTypeNo: param?.selectplantlist[0]
      };
      this.plantVarietyNo = ''
      nowstage.getPlantVariety(params).then(res => {
        if (res.code !== 1) {
          return;
        }
        this.plantVarietyList = res.data;
        this.formConfig[5].options = res.data;
      })
    },
    startVal (e) {
      this.$set(this.searchlist, 'startTime', e)
    },
    endVal (e) {
      this.$set(this.searchlist, 'endTime', e)
    },
    // 表格查询
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        sortList: this.sortList || [],
        entity: {
          deleteFlag: false,
          batchType: this.batchType === 0 ? 'BATCH' : 'SINGLE',
          batchName: this.searchlist.batchName,
          batchNo: this.searchlist.batchNo,
          lesseeNo: this.searchlist.lesseeNo,
          farmingTypeNo: getToken("farmingTypeNo"),
          organizationNo: getToken("organizationNo"),
          status: this.nowbatchstau,
          plantingTypeNo: this.searchlist.selectplantlist && this.searchlist.selectplantlist[0],
          varietyNo: this.searchlist.plantVarietyNo,
          facilityNo: this.searchlist.facilityNo,
          // assetDate: this.searchlist.assetDate
          startTime: this.searchlist.date && this.dateToFormattwo(this.searchlist.date[0]),
          endTime: this.searchlist.date && this.dateToFormattwo(this.searchlist.date[1]),
        }
      };
      this.entity = params.entity
      nowpagereq.gettablelist(params).then(res => {
        this.loading = false;
        if (res.code === 1) {
          // this.$message.success('查询成功')
        } else {
          this.$message.error("查询失败");
        }
        let data = res.data.content;
        this.tableData = data;
        console.log( this.tableData )
        // 赋值总条数
        this.totalSize = res.data.totalElements;
        // 赋值数组
        // this.tableData = data;
        this.addblankmet()
        this.resetActionBar();
      });
      // 判断搜索输入框数据
    },
    search() {
      // console.log(22222222);
      this.currentPage = 1;
      this.getTableDataList();
    },
    // 生产批次查询
    batchstaumet(i) {
      if (i == 0) {
        this.nowbatchstau = null;
      } else if (i == 1) {
        this.nowbatchstau = 0;
      } else {
        this.nowbatchstau = 1;
      }
      this.tableData = [];
      this.search();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    async dbhandleEdit(row, type) {
      this.dialogtitle = "查看";
      this.nowChanceStau = type || "";
      this.canInput = type ? true : false;
      const { data: rows } = await nowpagereq.querybatch(row.batchNo);
      this.formData = { ...rows, singleNoList: row.singleNos?.split(',') };
      // this.$set(this.formData, "batchName", rows.batchName)
      // this.$set(this.formData, "batchNo", rows.batchNo)
      // this.$set(this.formData, "mode", rows.mode)
      // this.$set(this.formData, "completionDays", rows.completionDays)
      // this.$set(this.formData, "lesseeName", rows.lesseeName)
      // this.$set(this.formData, "lesseeNo", rows.lesseeNo)
      // this.$set(this.formData, "plantingTypeNo", rows.plantingTypeNo)
      // this.$set(this.formData, "varietyNo", rows.varietyNo)
      // this.$set(this.formData, "cycle", rows.cycle)
      // this.$set(this.formData, "area", rows.area)
      // this.$set(this.formData, "areaUnitNo", rows.areaUnitNo)
      // this.$set(this.formData, "assetDate", rows.assetDate)
      // // this.$set(this.formDataays, "selectfacilyindexlist", rows.selectfacilyindexlist)
      // this.$set(this.formData, "assetValue", rows.assetValue)
      // this.$set(this.formData, "assetUnitNo", rows.assetUnitNo)
      // this.$set(this.formData, "description", rows.description)
      // console.log(rows)
      if (rows !== undefined) {
        if (rows.batchFacilityMapperList) {
          this.formData.selectfacilyindexlist = rows.batchFacilityMapperList.map(
            item => item.facilityNo
          );
        }
      }
      this.getvarriety(row.plantVarietyNo);
      // this.getpingzghongname(row.plantingTypeNo);
      // console.log(this.dialogtitle);
      // setTimeout(() => {
      this.dialogFormVisible = true;
      // this.$refs['formData'].resetFields();
      // }, 20)
    },
    handleSelectionChange(list) {
      this.nowSelectList = [];
      this.nowSelectList = list.map(item => item.batchNo)
      if (this.nowSelectList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    selectable(row, index) {
      // console.log(row)
      if (row.batchNo !== undefined) {
        // this.$message.warning('1')
        return row.batchNo // 通过某个值来进行判断，规定那一行的选择框被禁用
      }
    },
    // 删除时触发方法
    delmessage() {
      nowpagereq.dellist([this.nowSelectList[0]]).then(res => {
        if (res.code === 1) {
          this.$message.success("删除成功！");
          this.getTableDataList();
        } else {
          this.$message.error(res.msg || "删除失败！");
        }
      });
    },
    async add() {
      this.canInput = true;
      this.nowChanceStau = "add";
      this.formData = {
        batchNo: await this.addcode(),
        selectfacilyindexlist: [],
        batchFacilityMapperList: []
      };
      this.addActive = false;
      this.delActive = false;
      this.saveActive = true;
      this.cancelActive = true;
      this.editActive = false;
      this.dialogtitle = "添加";
      if (!this.formData.batchNo) {
        this.$message.error("批次号请求失败！");
        this.addActive = true;
        return
      }
      this.dialogFormVisible = true;
      let _self = this;
      _self.$nextTick(() => {
        // _self.ruleForm  为页面属性接收值   //officeType 为下拉框v-model对应的值
        _self.$set(_self.formData, "selectfacilyindexlist", []);
      });
    },
    // 取消
    async cancel(formData) {
      // this.nowChanceStau = 'cancel'
      this.nowChanceStau = "";
      this.formData = {}
      this.formData = {
        selectfacilyindexlist: [],
        batchFacilityMapperList: []
        // status: false
      };
      this.canInput = false;
      this.addActive = true;
      this.delActive = false;
      this.saveActive = false;
      this.cancelActive = false;
      this.editActive = false;
      this.$refs["formData"].resetFields();
      this.dialogFormVisible = false;
      // if (formData) {
      // }
      this.$refs.batchTableData.clearSelection()
    },
    assetVData(val) {
      if (this.formData.selectfacilyindexlist.length === 0) {
        return false;
      } else {
        // console.log(this.formData.selectfacilyindexlist, val);
        let params = {
          facilityNoList: this.formData.selectfacilyindexlist,
          assetValue: val
        };
        return nowpagereq.queryIfOverload(params).then(res => {
          return res.data;
        });
      }
    },
    handleDelete(data) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      }).then(() => {
        nowpagereq.del(data.batchNo).then((res) => {
          if (res.code === 1) {
            this.getTableDataList();
            this.$message.success("删除成功");
          } else {
            this.$message.error(res.msg || "删除失败");
          }
        });
      })
    },
    async save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          this.dialogRecVisible = true;
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    async saveAdd() {
      let dikauilist = [];
      this.formData.selectfacilyindexlist.forEach(item => {
        this.facilyList.forEach(items => {
          if (items.facilityNo === item) {
            dikauilist.push({
              facilityNo: items.facilityNo,
              facilityName: items.facilityName
            });
          }
        });
      });
      let partwo = this.formData;
      // 新增接口
      let zhparams = {
        ...partwo,
        // "batchNo": batchNo,
        batchFacilityMapperList: dikauilist,
        farmingTypeNo: this.farmingTypeNo,
        organizationNo: sessionStorage.organizationNo,
        batchType: this.batchType === 0 ? 'BATCH' : 'SINGLE',
      };
      // console.log(orgidlist, dikauilist)
      // console.log(zhparams)
      // if (zhparams.organizationNo === "") {
      //   orgidlist = Array.from(new Set(orgidlist));
      //   if (orgidlist.length > 1) {
      //     console.log(orgidlist);
      //     this.$message.error("设施组织结构不同！");
      //   } else if (orgidlist.length === 1) {
      //     zhparams.lessesNo = orgidlist[0];
      //     zhparams.organizationNo = orgidlist[0];
      //   } else {
      //     this.$message.warning("请选择设施!");
      //     return;
      //   }
      // }
      // delete this.zhparams.selectfacilyindexlist
      // console.log(zhparams)
      // return;
      let api = this.nowChanceStau == "add" ? 'addlist' : 'editlist'
      nowpagereq[api](zhparams).then(res => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.getselectdatalist();
          this.getBatchList();
          this.getTableDataList();
          this.dialogRecVisible = false;
          this.cancel();
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          this.cancel("formData");
          done();
        })
        .catch(_ => {});
    },
    numChange(field) {
      this.formData[field] < 0 && (this.formData[field] = 0)
    },
    // areaUnitlist
    async areaUnitlist(e) {
      const { data: unitName } = await nowpagereq.queryunit(e);
      this.formData.areaUnit = unitName.unitName;
    },
    // 当点击地块组时，查询地块组下的地块
    groupfacilychange(e) {
      this.formData.selectfacilyindexlist = []
      if (e) {
        landgroupInfoManage.getdikuaiGroup(e).then(res => {
          this.facilyList = res.data.filter(el => { return el.facilityTypeName == '种养设施' });
          this.formConfig[2].options = res.data;
        });
      } else {
        this.facilyList = this.allfacilyList.filter(el => { return el.facilityTypeName == '种养设施' })
      }
    },
    // 通过种养类别id查品种
    getpingzghong(e) {
      // alert("e")
      if (e) {
        let params = {
          plantTypeNo: e
        };
        zhongyangpizhong.querybycondition(params).then(res => {
          this.nowvarietyList = res.data;
          if (this.nowvarietyList[0]) {
            this.$set(this.formData, "varietyNo", this.nowvarietyList[0].plantVarietyNo)
            // this.formData[
            //   "varietyNo"
            // ] = this.nowvarietyList[0].plantVarietyNo;
          } else {
            this.$set(this.formData, "varietyNo", "")
            // this.formData["varietyNo"] = "";
          }
        });
        // this.getpingzghongname(e);
      } else {
        this.$set(this.formData, "varietyNo", "")
        // this.formData["varietyNo"] = "";
      }
    },
    // 通过种养类别id查种养名称
    // getpingzghongname(No) {
    //   let params = {
    //     plantTypeNo: No
    //   };
    //   zhongyangleibie.querybycondition(params).then(res => {
    //     this.nowplantTypeName = res.data[0].plantingTypeName;
    //     // console.log(this.nowplantTypeName)
    //   });
    // },
    // 通过种养品种id查品种name
    getvarriety(No) {
      let params = {
        plantVarietyNo: No
      };
      zhongyangpizhong.querybycondition(params).then(res => {
        this.nowvarietyList = res.data;
      });
    },
    // 循环过滤树形数组
    filterArrForKey(arr) {
      let newArr = [];
      newArr = arr?.map(item => {
        if (item.children) {
          item = {
            ...item,
            children: this.filterArrForKey(item.children)
          };
        }
        return item;
      });
      newArr = newArr?.filter(item => item != null);
      return newArr;
    }
  }
};
</script>

<style scoped lang="scss">
.dialogRec {
  ::v-deep .el-dialog {
    // margin-top: 15vh !important;
    width: 55% !important;
    .el-dialog__body {
      text-align: center;
      font-size: 18px;
      // color: red;
      letter-spacing: 2px;
      font-weight: 600;
      span {
        line-height: 100px;
      }
    }
    .el-dialog__footer {
      .Reconfirmation {
        background-color: #096f8f;
        border-radius: 6px;
        color: #fff;
      }
      .correct {
        background-color: #fff;
        color: #096f8f;
        border-radius: 6px;
        border: 1px solid #096f8f;
      }
    }
  }
}
::v-deep .el-table--medium td {
  padding: 10px 0 !important;
}

//  覆盖表单校验样式
::v-deep .el-form-item.is-error {
  .el-input__inner {
    border-color: #f56c6c !important;
  }
}
::v-deep .el-table__header-wrapper .el-table-column--selection{
  border: 1px solid red;
  // text-indent: -999999px;
  // display: none !important;
}

.facility-list{
  display: flex;
  justify-content: flex-start;
    flex-direction: row;
    flex-wrap: wrap;
  .facility-item{
    width: 400px;
    max-width: 30%;
    min-width: 30%;
    margin-right: 3%;
    margin-bottom: 10px;
    // height: 80px;
    border-radius: 5px;
    // border: 1px solid #ccc;
    box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.15);
    padding: 10px 20px;

    .info-line{
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
      font-size: 14px;
      &:not(:last-child){
        margin-bottom: 10px;
      }
      .name{
        text-align: left;
        width: 80px;
        flex-shrink: 0;
      }
      .value{
        width: 100%;
        text-align: left;
        font-weight: normal;
      }
    }
  }
}

::v-deep .tab-select {
  width: 100%;
  .butt-list-sty {
    position: absolute;
    left: 5px;
    top: 7px;
  }
}
</style>
